package main

import (
	"fmt"
	"io"
	"net"
	znet "zinx/Znet"
)

func main() {

	//创建Socket
	listener, err := net.Listen("tcp", "127.0.0.1:7777")
	if err != nil {

		fmt.Println("server listen err:", err)
		return
	}
	go func() {
		for {
			conn, err := listener.Accept()
			if err != nil {
				fmt.Println("server accept err:", err)
				continue
			}
			go func(conn net.Conn) {
				//处理客户端请求
				dp := znet.NewDataPack()
				for {

					//拆包过程
					//第一次从conn中，把包的head读取出来
					//缓冲的长度设置位，dp.GetHeadLen
					headdata := make([]byte, dp.GetHeadLen())
					//将缓冲区读满
					_, err := io.ReadFull(conn, headdata)
					if err != nil {
						fmt.Println("read head error")
						break
					}
					msghead, err := dp.UnPack(headdata)
					if err != nil {
						fmt.Println("server unpack err:", err)
						return
					}

					//读取数据
					if msghead.GetDataLen() > 0 {
						//接口类型断言，转化为具体类型*Message类型
						msg := msghead.(*znet.Message)
						msg.Data = make([]byte, msg.DataLen)
						_, err := io.ReadFull(conn, msg.Data)
						if err != nil {
							fmt.Println("server unpack data err:", err)
							return
						}
						fmt.Println("==> Recv Msg: ID=", msg.Id, ", len=", msg.DataLen, ", data=", string(msg.Data))
					}
				}
			}(conn)
		}
	}()

	select {}
}
